<template>
	<Container title="AI字帖" navColor="#2E5266" titleColor="#FFFFFF" pageColor="#f8f8f8">
		<view class="ai-dialog__container">
			<view class="ai-dialog__chat-area">
				<scroll-view scroll-y="true" class="message-list" :scroll-top="scrollTop">
					<div class="ai-dialog__message-box">
						<Recommend @recommend-select="handleRecommendSelect" />
						<view v-for="(message, index) in messages" :key="index" class="ai-dialog__message-item">
							<view
								:class="['ai-dialog__message', message.role === 'user' ? 'ai-dialog__message--user' : 'ai-dialog__message--ai']">
								<text class="ai-dialog__message-text">{{ message.content }}</text>
							</view>
						</view>
						<view v-if="loading" class="ai-dialog__message-item ai-dialog__message-item--loading">
							<view class="ai-dialog__message ai-dialog__message--ai">
								<text class="ai-dialog__message-text">正在回复中...</text>
							</view>
						</view>
					</div>

				</scroll-view>
			</view>

			<!-- 推荐组件 -->


			<view class="ai-dialog__input-area">
				<input class="ai-dialog__input-field" v-model="inputText" placeholder="请输入您的问题..."
					@confirm="sendMessage" />
				<button class="ai-dialog__send-btn" @click="sendMessage" :disabled="loading || !inputText.trim()">
					{{ loading ? '发送中...' : '发送' }}
				</button>
			</view>
		</view>
	</Container>
</template>

<script>
	import Container from '@/components/Container/index.vue'
	import Recommend from '@/components/Recommend/index.vue'
	import {
		chatMessage
	} from '@/api/thirdParty/index.js'
	import {
		getMessage,
		addMessage
	} from '@/api/zitie/index.js'
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			Container,
			Recommend
		},
		data() {
			return {
				inputText: '',
				messages: [],
				loading: false,
				userId: null,
				deviceId: null,
				scrollTop: 0
			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		watch: {
			messages: {
				handler() {
					// 深度监听messages变化，自动滚动到底部
					this.$nextTick(() => {
						this.scrollToBottom()
					})
				},
				deep: true
			}
		},
		onLoad() {
			this.handleGetMessage()
		},
		methods: {
			// 初始化用户信息
			// 获取历史消息
			async handleGetMessage() {
				try {
					const {
						data: {
							records
						}
					} = await getMessage({
						pageNum: 1,
						pageSize: 10
					})
					this.messages = records || []
				} catch (error) {
					console.error('获取历史消息失败:', error)
					this.messages = []
				}
			},

			// 设置消息角色
			setMessageByRole(content, role) {
				const newMessage = {
					content,
					role,
					timestamp: new Date()
				}
				this.messages.push(newMessage)

				return newMessage
			},

			// 滚动到底部
			scrollToBottom() {
				this.scrollTop = this.scrollTop === 99999 ? 99998 : 99999
			},

			// 处理推荐选项点击
			handleRecommendSelect(data) {
				console.log('推荐选项被选中:', data)

				// 使用拼接好的完整文本作为用户输入
				this.inputText = data.fullText

				// 自动发送消息
				this.sendMessage()
			},

			// 找到最新的assistant消息
			findLatestAssistant() {
				const currentList = [...this.messages]
				const lastIndex = currentList.length - 1
				const findItem = currentList[lastIndex]
				return {
					findItem,
					currentList
				}
			},

			// 删除最新的assistant消息
			deleteLatestAssistant() {
				if (this.messages.length > 0) {
					this.messages.splice(this.messages.length - 1, 1)
				}
			},

			// 发送消息
			async sendMessage() {
				if (!this.inputText.trim() || this.loading) return

				const userInput = this.inputText
				this.inputText = ''

				try {
					// 添加用户消息
					const userMsg = this.setMessageByRole(userInput, 'user')

					// 保存用户消息到服务器
					const allMsgRes = await addMessage({
						userId: this.userInfo.id,
						...userMsg
					})

					// 添加空的assistant消息用于流式更新
					this.setMessageByRole('', 'assistant')
					this.loading = true

					// 调用流式聊天API
					await chatMessage({
							messages: allMsgRes.data
						},
						(data) => {
							const lastIndex = this.messages.length - 1
							// 使用$set确保响应式更新
							this.$set(this.messages[lastIndex], 'content', this.messages[lastIndex].content + data)

						},
						(error) => {
							console.error('聊天流式响应错误:', error)
							this.deleteLatestAssistant()
							// 添加错误提示消息
							this.setMessageByRole('抱歉，服务出现异常，请稍后重试。', 'assistant')
						}, async () => {
							const lastIndex = this.messages.length - 1
							const findItem = this.messages[lastIndex]
							if (findItem && findItem.content && findItem.content.trim()) {
								await addMessage({
									userId: this.userInfo.id,
									...findItem
								})
							} else {
								this.deleteLatestAssistant()
							}
						}
					)

					// 流式对话完成后，保存AI回复到数据库


				} catch (error) {
					console.error('发送消息失败:', error)
					const errorMessage = this.setMessageByRole('抱歉，发送消息失败，请稍后重试。', 'assistant')
					// 保存错误消息到数据库
					try {
						await addMessage({
							userId: this.userInfo.id,
							...errorMessage
						})
					} catch (saveError) {
						console.error('保存错误消息失败:', saveError)
					}
				} finally {
					this.loading = false
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 主题变量已移至全局 assets/theme-variables.scss
	// Theme variables moved to global assets/theme-variables.scss

	.ai-dialog {

		// 主容器 - 仿古籍设计
		&__container {
			display: flex;
			flex-direction: column;
			height: calc(100vh - 88px);
			background: var(--gradient-paper);
			position: relative;

			// 添加纸张纹理效果
			&::before {
				content: '';
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-image:
					radial-gradient(circle at 20% 80%, rgba(120, 119, 116, 0.03) 0%, transparent 50%),
					radial-gradient(circle at 80% 20%, rgba(120, 119, 116, 0.03) 0%, transparent 50%),
					radial-gradient(circle at 40% 40%, rgba(120, 119, 116, 0.02) 0%, transparent 50%);
				pointer-events: none;
				z-index: 0;
			}
		}

		// 聊天区域 - 书卷展开效果
		&__chat-area {
			flex: 1;
			height: 0;

			position: relative;
			z-index: 1;

			.message-list {
				height: 100%;

				// 添加书页渐现动画
				&::-webkit-scrollbar {
					display: none;
				}

				// 仿古书边距线
				&::before {
					content: '';
					position: absolute;
					left: 40rpx;
					top: 0;
					bottom: 0;
					width: 2rpx;
					background: linear-gradient(to bottom,
							transparent 0%,
							var(--bronze) 10%,
							var(--bronze) 90%,
							transparent 100%);
					opacity: 0.3;
				}
			}
		}

		&__message-box {
			padding: 32rpx 24rpx;
		}

		// 消息项 - 水墨晕染进场效果
		&__message-item {
			margin-bottom: 32rpx;
			animation: messageAppear 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);
			transform-origin: left center;

			&--loading {
				.ai-dialog__message-text {
					opacity: 0.7;
					position: relative;

					// 水墨扩散动画
					&::after {
						content: '';
						position: absolute;
						top: 50%;
						right: -40rpx;
						width: 20rpx;
						height: 20rpx;
						border-radius: 50%;
						background: var(--ink-gray);
						opacity: 0.6;
						animation: inkDrop 1.5s infinite ease-in-out;
					}
				}
			}

			// 用户消息从右侧滑入
			&:has(.ai-dialog__message--user) {
				animation: messageSlideInRight 0.6s ease-out;
			}

			// AI消息从左侧墨迹晕染进入
			&:has(.ai-dialog__message--ai) {
				animation: messageInkSpread 0.8s ease-out;
			}
		}

		// 消息气泡 - 仿水墨画风格
		&__message {
			max-width: 75%;
			padding: 24rpx 32rpx;
			position: relative;
			backdrop-filter: blur(8rpx);

			// 消息气泡通用阴影
			box-shadow:
				0 4rpx 20rpx var(--shadow-soft),
				0 1rpx 3rpx var(--shadow-ink);

			&--user {
				background: var(--gradient-primary);
				color: var(--paper-white);
				margin-left: auto;
				text-align: right;
				border-radius: 32rpx 32rpx 8rpx 32rpx;

				// 印章效果  
				&::before {
					content: '';
					position: absolute;
					top: -4rpx;
					right: -4rpx;
					width: 16rpx;
					height: 16rpx;
					background: var(--primary-accent);
					border-radius: 50%;
					opacity: 0.8;
				}

				// 用户消息特殊纹理
				&::after {
					content: '';
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background-image: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
					border-radius: inherit;
					pointer-events: none;
				}
			}

			&--ai {
				background: var(--paper-white);
				color: var(--ink-black);
				margin-right: auto;
				border-radius: 32rpx 32rpx 32rpx 8rpx;
				border: 2rpx solid rgba(139, 69, 19, 0.1);

				// AI消息左侧装饰线条
				&::before {
					content: '';
					position: absolute;
					left: -8rpx;
					top: 20rpx;
					bottom: 20rpx;
					width: 4rpx;
					background: linear-gradient(to bottom,
							var(--primary-light) 0%,
							var(--primary-dark) 100%);
					border-radius: 2rpx;
					opacity: 0.8;
				}
			}
		}

		// 消息文本 - 书法字体风格
		&__message-text {
			font-size: 32rpx;
			line-height: 1.8;
			font-weight: 400;
			letter-spacing: 0.5rpx;

			// 为中文文本优化
			font-family:
				-apple-system,
				'PingFang SC',
				'Hiragino Sans GB',
				'Microsoft YaHei',
				'Source Han Sans CN',
				sans-serif;

			// 文字渐现效果
			animation: textReveal 0.6s ease-out 0.2s both;
		}

		// 输入区域 - 古典装饰边框
		&__input-area {
			display: flex;
			padding: 24rpx;
			background: rgba(253, 251, 247, 0.95);
			backdrop-filter: blur(20rpx);
			align-items: center;
			border-top: 2rpx solid rgba(139, 69, 19, 0.1);
			position: relative;
			z-index: 2;

			// 顶部装饰线
			&::before {
				content: '';
				position: absolute;
				top: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 120rpx;
				height: 4rpx;
				background: linear-gradient(90deg,
						transparent 0%,
						var(--bronze) 20%,
						var(--imperial-yellow) 50%,
						var(--bronze) 80%,
						transparent 100%);
				border-radius: 2rpx;
			}
		}

		// 输入框 - 仿古书页效果
		&__input-field {
			flex: 1;
			padding: 20rpx 28rpx;
			border: 2rpx solid rgba(139, 69, 19, 0.2);
			border-radius: 50rpx;
			margin-right: 20rpx;
			font-size: 30rpx;
			background: var(--paper-white);
			color: var(--ink-black);
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

			&::placeholder {
				color: rgba(74, 74, 74, 0.6);
				font-style: italic;
			}

			&:focus {
				border-color: var(--primary-light);
				box-shadow:
					0 0 0 4rpx rgba(74, 144, 164, 0.1),
					0 4rpx 12rpx var(--shadow-soft);
				outline: none;
			}
		}

		// 发送按钮 - 印章风格
		&__send-btn {
			background: var(--gradient-primary);
			color: var(--paper-white);
			border: none;
			padding: 20rpx 32rpx;
			border-radius: 50rpx;
			font-size: 28rpx;
			font-weight: 500;
			letter-spacing: 1rpx;
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
			position: relative;
			overflow: hidden;

			// 按钮装饰效果
			&::before {
				content: '';
				position: absolute;
				top: 0;
				left: -100%;
				width: 100%;
				height: 100%;
				background: linear-gradient(90deg,
						transparent 0%,
						rgba(255, 255, 255, 0.2) 50%,
						transparent 100%);
				transition: left 0.6s ease-out;
			}

			&:not(:disabled):active {
				transform: scale(0.98);

				&::before {
					left: 100%;
				}
			}

			&:disabled {
				background: rgba(74, 74, 74, 0.3);
				color: rgba(253, 251, 247, 0.6);
				cursor: not-allowed;
			}
		}
	}

	// 动画定义
	@keyframes messageAppear {
		0% {
			opacity: 0;
			transform: translateY(20rpx) scale(0.95);
		}

		100% {
			opacity: 1;
			transform: translateY(0) scale(1);
		}
	}

	@keyframes messageSlideInRight {
		0% {
			opacity: 0;
			transform: translateX(100rpx);
		}

		100% {
			opacity: 1;
			transform: translateX(0);
		}
	}

	@keyframes messageInkSpread {
		0% {
			opacity: 0;
			transform: translateX(-30rpx) scale(0.8);
			filter: blur(4rpx);
		}

		60% {
			opacity: 0.8;
			transform: translateX(-5rpx) scale(1.02);
			filter: blur(1rpx);
		}

		100% {
			opacity: 1;
			transform: translateX(0) scale(1);
			filter: blur(0);
		}
	}

	@keyframes inkDrop {

		0%,
		100% {
			opacity: 0.6;
			transform: scale(1);
		}

		50% {
			opacity: 0.2;
			transform: scale(1.5);
		}
	}

	@keyframes textReveal {
		0% {
			opacity: 0;
			transform: translateY(10rpx);
		}

		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	// 响应式设计
	@media (max-width: 750rpx) {
		.ai-dialog {
			&__message {
				max-width: 85%;
				padding: 20rpx 24rpx;

				&-text {
					font-size: 30rpx;
					line-height: 1.7;
				}
			}

			&__input-area {
				padding: 20rpx 16rpx;
			}
		}
	}
</style>